const api = require('../../../api/mop_api');
import { toast, log, err, to } from '../../../utils/wxapi';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    page: 1,
    size: 20,
    pageTotal: 0,
    board: 30,
    zhuolist: [],
    item: [],
    active: 0,
    nav: [
      {
        name: '未打印',
        isFirst: 0,
      },
      {
        name: '已打印',
        isFirst: 1,
      },
    ],
  },
  async onShow() {
    this.ordlist();
  },
  async zhuolist() {
    try {
      const res = api.board_list({ page: 1, size: 50 });
      if (res.respCode === 200) {
        let zhuolist = JSON.parse(res.source);
        this.setData({
          zhuolist,
        });
        wx.hideLoading();
        this.zhuo();
      } else {
        toast(res.msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  async ordlist() {
    try {
      const { page, size, nav, active } = this.data;
      const data = { isFirst: nav[active].isFirst };
      const res = await api.orderlist({ page, size, data });
      const list = JSON.parse(res.source);
      log(list);
      if (this.data.list.length === 0) {
        this.setData({
          list,
          pageTotal: res.pageTotal,
        });
      } else {
        this.setData({
          list: this.data.list.concat(list),
          pageTotal: res.pageTotal,
        });
      }
      this.zhuolist();
    } catch (error) {
      err(error);
      throw error;
    }
  },
  zhuo() {
    try {
      const { list, zhuolist } = this.data;
      const zhuoMap = new Map(zhuolist.map(v => [v.id, v.markNo]));
      list.forEach(e => {
        const markNo = zhuoMap.get(e.deskId);
        if (markNo) {
          e.deskNo = markNo;
        }
      });
      log(list);
      this.setData({ list });
    } catch (error) {
      err(error);
      throw error;
    }
  },
  onChange(e) {
    this.setData({
      active: e.detail.index,
      list: [],
      page: 1,
    });
    this.ordlist();
  },

  onHide() {
    this.setData({
      page: 1,
      list: [],
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    try {
      this.setData({
        page: 1,
        list: [],
      });
      await this.ordlist();
      toast('更新成功');
    } catch (error) {
      log(error);
    } finally {
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let { list, pageTotal, page } = this.data;
    if (list.length < pageTotal) {
      this.setData({
        page: page + 1,
      });
      this.ordlist();
    } else {
      toast('已加载全部数据');
    }
  },
});
